﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Process.API.Application.Command.Show;
using Process.API.DTOs;
using Process.Domain;
using Process.ErrorCode;
using Process.Infrastructure.Interface;

namespace Process.API.Application.Handler.Show
{
    public class ProductionProcessTableHandler : IRequestHandler<ProductionProcessTableCommand, APIResult<List<ProductionProcessTableDto>>>
    {
        private readonly IBaseRepository<ProductionProcessTable> proRep;
        private readonly IBaseRepository<ProcessTable> processRep;

        public ProductionProcessTableHandler(IBaseRepository<ProductionProcessTable> proRep, IBaseRepository<ProcessTable> processRep)
        {
            this.proRep = proRep;
            this.processRep = processRep;
        }

        public async Task<APIResult<List<ProductionProcessTableDto>>> Handle(ProductionProcessTableCommand request, CancellationToken cancellationToken)
        {
            var query =
                from ppt in proRep.GetAll().Where(x => !x.IsDel)
                join pt in processRep.GetAll() on ppt.ProcessId equals pt.ProcessId into gj
                from pt in gj.DefaultIfEmpty()
                select new ProductionProcessTableDto
                {
                    ProductionProcessId = ppt.ProductionProcessId,
                    ProcessNumber = ppt.ProcessNumber,
                    ProductionOrdersId = ppt.ProductionOrdersId,
                    ProcessId = ppt.ProcessId,
                    ProcessCode = pt == null ? string.Empty : pt.ProcessCode,
                    ProcessName = pt == null ? null : pt.ProcessName,
                    State = pt == null ? 0 : pt.State,
                    ProcessDescription = pt == null ? string.Empty : pt.ProcessDescription,
                    Remark = pt == null ? string.Empty : pt.Remark,
                    IsDel = ppt.IsDel
                };

            if (request.ProductionOrdersId != 0)
            {
                query = query.Where(x => x.ProductionOrdersId == request.ProductionOrdersId);
            }

            if (request.ProcessNumber != 0)
            {
                query = query.Where(x => x.ProcessNumber == request.ProcessNumber);
            }

            var list = await query.ToListAsync(cancellationToken);

            return new APIResult<List<ProductionProcessTableDto>>
            {
                Code = APIEnum.Ok,
                Message = "生产工单工序查询成功",
                Data = list
            };
        }
    }
}
